#include "BlockQueue.hpp"
#include "task.hpp"
// 任务版  多生产者多消费者
void *Producer(void *args)
{
    BlockQueue<task> *bq = (BlockQueue<task> *)args;
    string s = "+-*/";
    while (true)
    {
        sleep(1);
        int x = rand() % 10;
        usleep(rand()%1000);
        int y = rand() % 5 + 1;

        char op = s[rand() % 4];
        task t(x, y, op);
        bq->Push(t);
        cout << "生产者->" << pthread_self()<<" " << "produce a task:" << x << op << y << "=?" << endl;
    }
}
void *Consumer(void *args)
{
    BlockQueue<task> *bq = (BlockQueue<task> *)args;
    while(true)
    {
    //sleep(1);
    task t;
    bq->Pop(&t);
    int result=t.count();
    cout<<"消费者->"<<pthread_self()<<" "<<"get a task:"<<t.getX()<<t.getOP()<<t.getY()<<"="<<result<<endl;
    }
   
    

}
int main()
{
    srand(time(nullptr) ^ getpid() ^ 0x23);
    pthread_t p1, p2, c1, c2;
    BlockQueue<task> *bq = new BlockQueue<task>;
    pthread_create(&p1, nullptr, Producer, (void *)bq);
    pthread_create(&p2, nullptr, Producer, (void *)bq);
    pthread_create(&c1, nullptr, Consumer, (void *)bq);
    pthread_create(&c2, nullptr, Consumer, (void *)bq);
    pthread_join(p1, nullptr);
    pthread_join(p2, nullptr);
    pthread_join(c1, nullptr);
    pthread_join(c2, nullptr);
    delete bq;

    return 0;
}








//单生产者消费者
/* void *consumer(void *args)
{

    BlockQueue<int> *bq = (BlockQueue<int> *)args;
    int i = 0;
    while (true)
    {
        sleep(1);
        bq->Push(i);
        cout << "生产者"
             << "->" << i << endl;
        i++;
    }
}
void *producer(void *args)
{
    BlockQueue<int> *bq = (BlockQueue<int> *)args;
    int i;
    while (true)
    {
        //sleep(1);
        bq->Pop(&i);
        cout << "消费者"
             << "->" << i << endl;

    }
}

int main()
{
    pthread_t c, p;
    BlockQueue<int> *bq = new BlockQueue<int>();
    pthread_create(&c, nullptr, consumer, (void *)bq);
    pthread_create(&p, nullptr, producer, (void *)bq);
    pthread_join(c, nullptr);
    pthread_join(p, nullptr);

    return 0;
} */